<!-- 仓库管理 -->
<template>
  <div class="warehouse-management">
    <div class="title-section">
      <h2>仓库管理</h2>
      <div class="title-actions">
        <button class="btn-secondary" @click="testApiConnection" style="margin-right: 10px;">测试连接</button>
        <button class="btn-primary" @click="openCreateDialog">新建</button>
      </div>
    </div>

    <div class="controls-section">
      <div class="filters">
        <div class="filter-item">
          <label>仓库编码</label>
          <input v-model.trim="filters.warehouseCode" type="text" placeholder="请输入仓库编码">
        </div>
        <div class="filter-item">
          <label>仓库名称</label>
          <input v-model.trim="filters.warehouseName" type="text" placeholder="请输入仓库名称">
        </div>
        <div class="filter-item">
          <label>负责人</label>
          <input v-model.trim="filters.username" type="text" placeholder="请输入负责人用户名">
        </div>
        <div class="filter-item">
          <label>状态</label>
          <select v-model="filters.status">
            <option value="">全部</option>
            <option :value="0">启用</option>
            <option :value="1">停用</option>
          </select>
        </div>
      </div>
      <div class="actions">
        <button class="btn-primary" @click="handleSearch">搜索</button>
        <button class="btn-secondary" @click="handleReset">重置</button>
      </div>
    </div>

    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll"></th>
            <th>仓库编码</th>
            <th>仓库名称</th>
            <th>仓库负责人</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in tableData" :key="row.warehouseId || row.id || index">
            <td><input type="checkbox" v-model="row.selected" @change="updateSelectAll"></td>
            <td class="link-style" @click="viewById(row)">{{ row.warehouseCode || '-' }}</td>
            <td>{{ row.warehouseName || '-' }}</td>
            <td>{{ row.username || '-' }}</td>
            <td>{{ formatStatus(row.status) }}</td>
            <td>
              <button class="btn-secondary" @click="openEditDialog(row)">编辑</button>
              <button class="btn-secondary" style="margin-left: 8px;" @click="handleDelete(row)">删除</button>
            </td>
          </tr>
          <tr v-if="!loading && tableData.length === 0">
            <td colspan="6" style="text-align:center;color:#909399;">暂无数据</td>
          </tr>
          <tr v-if="loading">
            <td colspan="6" style="text-align:center;color:#909399;">加载中...</td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
        <label>全选</label>
        <button class="btn-secondary" @click="exportSelected" :disabled="exporting">{{ exporting ? '导出中...' : '导出' }}</button>
      </div>
      <div class="pagination">
        <button @click="prevPage" :disabled="currentPage === 1">&lt;</button>
        <button v-for="page in totalPages" :key="page" :class="{ active: currentPage === page }" @click="goToPage(page)">{{ page }}</button>
        <button @click="nextPage" :disabled="currentPage === totalPages">&gt;</button>
        <select v-model.number="pageSize" @change="handleSizeChange">
          <option :value="10">10条/页</option>
          <option :value="20">20条/页</option>
          <option :value="50">50条/页</option>
        </select>
      </div>
    </div>

    <!-- 新增/编辑 弹窗 -->
    <div v-if="dialog.visible" class="dialog-mask">
      <div class="dialog">
        <div class="dialog-header">
          <span>{{ dialog.isEdit ? '编辑仓库' : '新增仓库' }}</span>
          <span class="dialog-close" @click="closeDialog">×</span>
        </div>
        <div class="dialog-body">
          <div class="form-grid">
            <div class="form-item">
              <label>仓库编码</label>
              <input v-model.trim="dialog.form.warehouseCode" type="text" placeholder="可不填，后端自动生成">
            </div>
            <div class="form-item required">
              <label>仓库名称</label>
              <input v-model.trim="dialog.form.warehouseName" type="text" placeholder="请输入仓库名称">
            </div>
            <div class="form-item">
              <label>负责人ID</label>
              <input v-model.trim="dialog.form.userId" type="text" placeholder="请输入负责人用户ID">
            </div>
            <div class="form-item required">
              <label>状态</label>
              <select v-model.number="dialog.form.status">
                <option :value="0">启用</option>
                <option :value="1">停用</option>
              </select>
            </div>
          </div>
          <div v-if="dialog.error" class="form-error">{{ dialog.error }}</div>
        </div>
        <div class="dialog-footer">
          <button class="btn-secondary" @click="closeDialog">取消</button>
          <button class="btn-primary" style="margin-left: 8px;" :disabled="dialog.submitting" @click="submitDialog">{{ dialog.submitting ? '提交中...' : '保存' }}</button>
        </div>
      </div>
    </div>

    <!-- 详情 弹窗 -->
    <div v-if="detail.visible" class="dialog-mask">
      <div class="dialog">
        <div class="dialog-header">
          <span>仓库详情</span>
          <span class="dialog-close" @click="closeDetail">×</span>
        </div>
        <div class="dialog-body">
          <div v-if="detail.loading" style="text-align:center;color:#909399;">加载中...</div>
          <div v-else class="detail-grid">
            <div class="detail-item"><label>仓库编码</label><span>{{ detail.data.warehouseCode || '-' }}</span></div>
            <div class="detail-item"><label>仓库名称</label><span>{{ detail.data.warehouseName || '-' }}</span></div>
            <div class="detail-item"><label>负责人</label><span>{{ detail.data.username || '-' }}</span></div>
            <div class="detail-item"><label>状态</label><span>{{ formatStatus(detail.data.status) }}</span></div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn-primary" @click="closeDetail">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { warehouseApi } from '@/api/warehouse'

export default {
  name: 'WarehouseManagement',
  data() {
    return {
      loading: false,
      exporting: false,
      selectAll: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      filters: { warehouseCode: '', warehouseName: '', username: '', status: '' },
      tableData: [],
      dialog: {
        visible: false,
        isEdit: false,
        submitting: false,
        error: '',
        form: { warehouseId: undefined, warehouseCode: '', warehouseName: '', userId: '', status: 0 }
      },
      detail: { visible: false, loading: false, data: {} }
    }
  },
  computed: {
    totalPages() {
      return Math.max(1, Math.ceil(this.total / this.pageSize))
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      this.loading = true
      try {
        const params = {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          warehouseCode: this.filters.warehouseCode || undefined,
          warehouseName: this.filters.warehouseName || undefined,
          username: this.filters.username || undefined,
          status: this.filters.status === '' ? undefined : this.filters.status
        }
        console.log('请求参数:', params)
        console.log('请求URL:', '/warehouse/page')

        const res = await warehouseApi.page(params)
        console.log('API响应:', res)

        // 检查响应结构
        if (!res) {
          console.error('响应为空')
          this.tableData = []
          this.total = 0
          return
        }

        const payload = res?.data
        console.log('响应数据:', payload)

        // 尝试多种数据结构
        let pageData = payload?.data || payload
        if (!pageData) {
          console.warn('未找到分页数据，尝试直接使用payload')
          pageData = payload
        }

        console.log('分页数据:', pageData)

        // 尝试多种记录字段名
        let records = pageData?.records || pageData?.list || pageData?.data || []
        let total = pageData?.total || pageData?.totalElements || 0

        console.log('记录数:', records.length, '总数:', total)
        console.log('记录示例:', records[0])

        this.tableData = (records || []).map(r => ({
          ...r,
          selected: false
        }))
        this.total = total
        this.updateSelectAll()

        console.log('最终表格数据:', this.tableData)

      } catch (e) {
        console.error('获取仓库列表失败:', e)
        console.error('错误详情:', e.response || e)
        console.error('错误状态:', e.response?.status)
        console.error('错误数据:', e.response?.data)

        // 显示用户友好的错误信息
        if (e.response?.status === 404) {
          console.error('接口不存在，请检查后端服务是否启动')
        } else if (e.response?.status === 500) {
          console.error('后端服务错误')
        } else if (!e.response) {
          console.error('网络错误，请检查后端服务是否启动')
        }

        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    handleSearch() { this.currentPage = 1; this.fetchData() },
    handleReset() {
      this.filters = { warehouseCode: '', warehouseName: '', username: '', status: '' }
      this.currentPage = 1
      this.fetchData()
    },

    toggleSelectAll() { this.tableData.forEach(row => { row.selected = this.selectAll }) },
    updateSelectAll() {
      if (this.tableData.length === 0) { this.selectAll = false; return }
      this.selectAll = this.tableData.every(row => row.selected)
    },
    prevPage() { if (this.currentPage > 1) { this.currentPage--; this.fetchData() } },
    nextPage() { if (this.currentPage < this.totalPages) { this.currentPage++; this.fetchData() } },
    goToPage(page) { if (page !== this.currentPage) { this.currentPage = page; this.fetchData() } },
    handleSizeChange() { this.currentPage = 1; this.fetchData() },

    formatStatus(s) { if (s === 0 || s === '0') return '启用'; if (s === 1 || s === '1') return '停用'; return '-' },

    async viewById(row) {
      try {
        this.detail.visible = true
        this.detail.loading = true
        const id = row.warehouseId || row.id
        console.log('查看仓库详情，行数据:', row)
        console.log('查看仓库详情，ID:', id)

        // 优先使用表格行的数据，确保显示一致
        let data = row

        // 如果表格行数据不完整，再尝试从API获取
        if (!row.warehouseName || row.warehouseName === '-') {
          try {
            const res = await warehouseApi.getById(id)
            console.log('获取详情响应:', res)
            if (res?.data) {
              data = res.data
            }
          } catch (apiError) {
            console.warn('API获取详情失败，使用表格行数据:', apiError)
          }
        }

        console.log('最终使用的数据:', data)

        // 直接使用表格行的数据，确保与表格显示一致
        this.detail.data = {
          warehouseId: row.warehouseId || row.id,
          warehouseCode: row.warehouseCode || '-',
          warehouseName: row.warehouseName || '-',
          username: row.username || '-',
          status: Number(row.status ?? 0)
        }

        console.log('设置到详情的数据:', this.detail.data)
      } catch (e) {
        console.error('获取仓库详情失败:', e)
        console.error('错误详情:', e.response || e)

        // 如果出错，使用当前行的数据
        this.detail.data = {
          warehouseId: row.warehouseId || row.id,
          warehouseCode: row.warehouseCode || '-',
          warehouseName: row.warehouseName || '-',
          username: row.username || '-',
          status: Number(row.status ?? 0)
        }
      } finally {
        this.detail.loading = false
      }
    },
    closeDetail() { this.detail.visible = false },

    resetDialogForm() {
      this.dialog.form = { warehouseId: undefined, warehouseCode: '', warehouseName: '', userId: '', status: 0 }
      this.dialog.error = ''
    },
    openCreateDialog() { this.dialog.isEdit = false; this.resetDialogForm(); this.dialog.visible = true },
    async openEditDialog(row) {
      try {
        this.dialog.isEdit = true
        this.dialog.error = ''
        const id = row.warehouseId || row.id
        console.log('编辑仓库，行数据:', row)
        console.log('编辑仓库，ID:', id)

        // 优先使用表格行的数据，确保与表格显示一致
        let detail = row

        // 如果表格行数据不完整，再尝试从API获取
        if (!row.warehouseName || row.warehouseName === '-') {
          try {
            const detailRes = await warehouseApi.getById(id)
            console.log('获取详情响应:', detailRes)
            if (detailRes?.data) {
              detail = detailRes.data
            }
          } catch (apiError) {
            console.warn('API获取详情失败，使用表格行数据:', apiError)
          }
        }

        console.log('最终使用的数据:', detail)

        // 直接使用表格行的数据，确保与表格显示一致
        this.dialog.form = {
          warehouseId: row.warehouseId || row.id,
          warehouseCode: row.warehouseCode || '',
          warehouseName: row.warehouseName || '',
          userId: row.userId || '',
          status: Number(row.status ?? 0)
        }

        console.log('设置到表单的数据:', this.dialog.form)
        this.dialog.visible = true
      } catch (e) {
        console.error('获取仓库详情失败:', e)
        console.error('错误详情:', e.response || e)

        // 如果出错，使用当前行的数据
        this.dialog.form = {
          warehouseId: row.warehouseId || row.id,
          warehouseCode: row.warehouseCode || '',
          warehouseName: row.warehouseName || '',
          userId: row.userId || '',
          status: Number(row.status ?? 0)
        }
        this.dialog.visible = true
      }
    },
    closeDialog() { if (!this.dialog.submitting) this.dialog.visible = false },
    validateDialogForm() {
      if (!this.dialog.form.warehouseName) { this.dialog.error = '请填写仓库名称'; return false }
      this.dialog.error = ''
      return true
    },
    async submitDialog() {
      if (!this.validateDialogForm()) return
      this.dialog.submitting = true
      try {
        const payload = { ...this.dialog.form }
        if (this.dialog.isEdit) {
          // 编辑时需要传递ID
          payload.id = payload.warehouseId
          await warehouseApi.update(payload)
        } else {
          // 新增时不需要传递ID
          delete payload.warehouseId
          if (!payload.warehouseCode) delete payload.warehouseCode
          await warehouseApi.add(payload)
        }
        this.dialog.visible = false
        this.fetchData()
      } catch (e) {
        console.error('保存仓库失败:', e)
      } finally {
        this.dialog.submitting = false
      }
    },

    async handleDelete(row) {
      const ok = window.confirm(`确认删除仓库：${row.warehouseName}？`)
      if (!ok) return
      try {
        const id = row.warehouseId || row.id
        await warehouseApi.delete(id)
        this.fetchData()
      } catch (e) {
        console.error('删除仓库失败:', e)
      }
    },

    exportSelected() {
      this.exporting = true
      try {
        const rows = this.tableData.filter(r => r.selected)
        const header = ['仓库编码','仓库名称','负责人','状态']
        const csvRows = [header.join(','), ...rows.map(r => [
          r.warehouseCode || '',
          r.warehouseName || '',
          r.username || '',
          this.formatStatus(r.status)
        ].map(v => `"${String(v).replace(/"/g,'""')}"`).join(','))]
        const blob = new Blob(["\ufeff" + csvRows.join('\n')], { type: 'text/csv;charset=utf-8;' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = '仓库导出.csv'
        a.click()
        URL.revokeObjectURL(url)
      } finally {
        this.exporting = false
      }
    },
    async testApiConnection() {
      try {
        const res = await warehouseApi.page({ pageNo: 1, pageSize: 1 })
        if (res && res.code === 200) {
          alert('API连接成功！')
          console.log('API连接成功:', res)
        } else {
          alert('API连接失败！')
          console.error('API连接失败:', res)
        }
      } catch (e) {
        alert('API连接失败！')
        console.error('API连接失败:', e)
      }
    }
  }
}
</script>

<style scoped>
.warehouse-management { padding: 20px; background-color: #f5f7fa; }
.title-section { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.title-section h2 { font-size: 20px; font-weight: bold; }
.title-actions { display: flex; align-items: center; gap: 10px; }
.controls-section { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 16px; padding: 20px; background-color: #fff; border-radius: 8px; margin-bottom: 20px; align-items: center; }
.filters { display: flex; flex-wrap: wrap; gap: 16px; align-items: center; }
.filter-item { display: flex; align-items: center; gap: 8px; }
.filter-item label { font-size: 14px; white-space: nowrap; }
.filter-item input, .filter-item select { padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; width: 150px; }
.actions { display: flex; gap: 10px; }
.btn-primary { background-color: #409eff; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.btn-secondary { background-color: #fff; color: #606266; border: 1px solid #dcdfe6; padding: 8px 16px; border-radius: 4px; cursor: pointer; }
.table-section { background-color: #fff; padding: 20px; border-radius: 8px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ebeef5; }
th { background-color: #f8f9fa; }
.link-style { color: #409eff; cursor: pointer; }
.footer-section { display: flex; justify-content: space-between; align-items: center; margin-top: 20px; background-color: #fff; padding: 10px 20px; border-radius: 8px; }
.footer-left { display: flex; align-items: center; gap: 8px; }
.pagination { display: flex; align-items: center; gap: 8px; }
.pagination button { padding: 6px 12px; border: 1px solid #dcdfe6; background-color: #fff; cursor: pointer; border-radius: 4px; }
.pagination button.active { background-color: #409eff; color: white; border-color: #409eff; }
.pagination select { padding: 6px; border: 1px solid #dcdfe6; border-radius: 4px; }

/* 弹窗同 UnitLibrary 风格 */
.dialog-mask { position: fixed; inset: 0; background: rgba(0,0,0,0.35); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.dialog { width: 720px; max-width: 92vw; background: #fff; border-radius: 8px; overflow: hidden; }
.dialog-header { padding: 12px 16px; border-bottom: 1px solid #ebeef5; display: flex; justify-content: space-between; align-items: center; font-weight: 600; }
.dialog-close { cursor: pointer; font-size: 18px; color: #909399; }
.dialog-body { padding: 16px; }
.dialog-footer { padding: 12px 16px; border-top: 1px solid #ebeef5; text-align: right; }
.form-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
.form-item { display: flex; flex-direction: column; gap: 6px; }
.form-item.required label::after { content: '*'; color: #f56c6c; margin-left: 4px; }
.form-item input, .form-item select { padding: 8px; border: 1px solid #dcdfe6; border-radius: 4px; }
.form-error { color: #f56c6c; font-size: 13px; margin-top: 8px; }
.detail-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
.detail-item { display: flex; align-items: center; gap: 8px; }
.detail-item label { color: #606266; }
</style>


